package xyz.scootaloo.mono.security.token

import xyz.scootaloo.mono.base.util.EncryptUtil
import xyz.scootaloo.mono.base.util.IpUtil
import xyz.scootaloo.mono.data.entity.auth.AuthUser
import xyz.scootaloo.mono.security.service.AccountService
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * 客户端标识
 *
 * 用户登陆成功后, 后端将为该用户签发jwt, 每个jwt有一个 [ClientID] 与之对应.
 *
 * [ClientID] 的作用是, 将常用的用户身份信息提取出来, 收集到一起, 在需要的时候能快速获取.
 * [AccountService.getCurrentClient] -> 用于获取当前登陆用户的信息.
 *
 * @param uid      用户在数据库中的唯一编号
 * @param ip       用户客户端的IP地址
 * @param appId    随机生成的随机数
 * @param roleCode 数据库中记录的用户角色编号
 * @param username 用户名
 * @param date     生成此标识的日期
 *
 * @author flutterdash@qq.com
 * @since 2021/9/24 23:01
 */
data class ClientID(
    val uid: Int,
    var ip: String,
    var appId: String,
    val roleCode: Int,
    val username: String,
    val date: Date = Date()
) {

    internal fun updateAppId() {
        appId = EncryptUtil.generateSalt(16)
    }

    internal fun updateIpAddress(request: HttpServletRequest) {
        ip = IpUtil.getRealIpAddress(request)
    }

    companion object StaticMethods {
        fun of(authUser: AuthUser): ClientID {
            return ClientID(
                uid = authUser.uid,
                ip = "",
                appId = "",
                roleCode = authUser.roleCode,
                username = authUser.username
            )
        }
    }
}
